<template>
	<!-- 统计易损性分析 -->
	<div class="app-container">
		<el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px">
			<div class="form-inline">
				<!-- <el-row justify="center">
					<el-col :span="11">
						<el-form-item label="烈度：" class="form-item" prop="intensity">
							<el-select v-model="params.intensity" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in intensityOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="破坏状态：" class="form-item" prop="damage"><el-input v-model="params.damage"
								placeholder="请输入" clearable /></el-form-item>
					</el-col>
				</el-row> -->
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="userName"><el-input v-model="params.userName"
								placeholder="请输入" clearable /></el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间：">
							<el-col :span="11">
								<el-form-item prop="createStartTime">
									<el-date-picker clearable v-model="params.createStartTime" type="date"
										placeholder="开始时间" value-format="YYYY-MM-DD" :disabled-date="startDisableDate"
										style="width: 100%" />
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="createEndTime">
									<el-date-picker clearable v-model="params.createEndTime" type="date" placeholder="结束时间"
										value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<!-- <el-col :span="11">
							<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
									<el-input v-model="params.maintainerUnit" placeholder="" clearable />
							</el-form-item>
					</el-col> -->
					<el-col :span="11">
						<el-form-item label="用途：">
							<el-col :span="12">
								<el-form-item prop="use0">
									<el-select v-model="params.use0" placeholder="请选择" class="form-select"
										@change="useChange" clearable>
										<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="use1">
									<el-select v-model="params.use1" placeholder="请选择" class="form-select" clearable>
										<el-option v-for="item in use1Options" :key="item.value" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="结构类型：">
							<el-col :span="12">
								<el-form-item prop="structureType">
									<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
										@change="structureTypeChange" clearable>
										<el-option v-for="item in structureTypeOptions" :key="item.value"
											:label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="structureType1">
									<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
										clearable>
										<el-option v-for="item in structureType1Options" :key="item.value"
											:label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="区域：" class="form-item" prop="region">
							<el-form-item prop="province" style="width:120px;margin-right:10px;">
								<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" clearable
									value-key="id">
									<el-option v-for="item in provinceData" :key="item.id" :label="item.name"
										:value="item"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="city" style="width:120px;margin-right:10px;">
								<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
									value-key="id">
									<el-option v-for="item in cityData" :key="item.id" :label="item.name"
										:value="item"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="county" style="width:120px;">
								<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
									value-key="id">
									<el-option v-for="item in areaData" :key="item.id" :label="item.name"
										:value="item"></el-option>
								</el-select>
							</el-form-item>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
							<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="建造年代：" class="form-item" prop="years">
							<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="是否在基础库：" class="form-item" prop="basicLibrary" v-show="isAdmin">
							<el-select v-model="params.basicLibrary" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in basicLibraryOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center" v-if="activeName === '2' || activeName === '3'">
					<el-col :span="11">
						<el-form-item label="是否计算：" class="form-item" prop="calculateOrNot" v-show="isAdmin">
							<el-select v-model="params.calculateOrNot" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in calculateOrNotOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11"></el-col>
				</el-row>
				<!-- 按钮 -->
				<el-row justify="end">
					<el-form-item class="bottom-button">
						<el-button type="primary" v-if="activeName === '2' || activeName === '3'"
							@click="onRecalculate">重新计算</el-button>
						<el-button type="primary" @click="onImport">导入</el-button>
						<el-button type="primary" @click="onCreateMatrix" v-if="activeName !== '4'">生成易损性矩阵</el-button>
						<el-button type="primary" @click="onSearch">查询</el-button>
						<el-button type="primary" @click="onRest">重置</el-button>
					</el-form-item>
				</el-row>
			</div>
		</el-form>

		<!-- tab -->
		<el-tabs v-model="activeName" type="card" @tab-click="handleClickTab">
			<el-tab-pane label="震害数据" name="1">
				<div class="table-wrapper"></div>
			</el-tab-pane>
			<el-tab-pane label="预测数据" name="2"></el-tab-pane>
			<el-tab-pane label="筛选数据" name="3"></el-tab-pane>
			<el-tab-pane label="生成的易损性矩阵" name="4"></el-tab-pane>
		</el-tabs>
		<el-radio-group v-if="activeName == '3'" v-model="params.dataSvType" style="margin-bottom: 10px;"
			@change="onChangeDataType">
			<el-radio :label="1">震害数据</el-radio>
			<el-radio :label="2">预测数据</el-radio>
			<el-radio :label="null">全部</el-radio>
		</el-radio-group>
		<!-- 表格 -->
		<el-table v-loading="loading" class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
			@selection-change="handleSelectionChange" @row-click="rowClick" :cell-style="{ border: '1px solid #e5ebf7' }"
			:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
			<el-table-column type="selection" width="55" label="序号" />
			<el-table-column prop="number" header-align="center" align="center" label="编号" width="150">
				<template #default="scope">
					<el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">{{ scope.row.number
					}}</el-button>
				</template>
			</el-table-column>
			<el-table-column prop="dataSourcesNums" header-align="center" align="center" label="原始数据编号" v-if="activeName=='4'"  show-overflow-tooltip />
			<el-table-column prop="region" header-align="center" align="center" label="区域" />
			<el-table-column prop="st" header-align="center" align="center" label="结构类型" />
			<el-table-column prop="years" header-align="center" align="center" label="建造年代" />
			<el-table-column prop="fortification" header-align="center" align="center" label="设防情况" width="100" />
			<el-table-column prop="cs" header-align="center" align="center" label="层数" width="80" />
			<el-table-column prop="userName" header-align="center" align="center" label="维护人" />
			<el-table-column prop="createTime" header-align="center" align="center" label="维护时间" />
			<!-- <el-table-column prop="intensity" header-align="center" align="center" label="烈度" width="100">
				<template #default="scope">
					<span v-if="scope.row.intensity" v-html="scope.row.intensity.replace(/;/g, '</br>')"></span>
				</template>
			</el-table-column>
			<el-table-column prop="damage" header-align="center" align="center" label="破坏状态">
				<template #default="scope">
					<span v-if="scope.row.damage" v-html="scope.row.damage.replace(/;/g, '</br>')"></span>
				</template>
			</el-table-column> -->
			<el-table-column prop="use" header-align="center" align="center" label="用途">
				<template #default="scope">
					<span>{{ getUseByOptions(scope.row.use0) }}-{{ getChildUseByOptions(scope.row.use0, scope.row.use1)
					}}</span>
				</template>
			</el-table-column>
			<!-- 预测、筛选数据显示是否已计算 -->
			<el-table-column prop="calculateOrNot" header-align="center" align="center" label="是否已计算" width="120"
				v-if="activeName == '2' || activeName == '3'">
				<template #default="scope">
					{{ scope.row.calculateOrNot === '1' ? '是' : scope.row.calculateOrNot === '0' ? '否' : '-' }}
				</template>
			</el-table-column>
			<el-table-column prop="basicLibrary" header-align="center" align="center" label="是否在基础库" width="120"
				v-if="activeName == '4' && isAdmin">
				<template #default="scope">{{ scope.row.basicLibrary === '1' ? '是' : '否' }}</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" align="center" width="180" v-if="activeName == '4' && isAdmin">
				<template #default="scope">
					<el-button :type="scope.row.basicLibrary && scope.row.basicLibrary.trim() == '1' ? 'danger' : 'success'"
						text size="small" @click="handleRemove(scope.row)">
						{{ scope.row.basicLibrary === '1' ? '移出管理库' : '移入管理库' }}
					</el-button>
					<el-button v-if="scope.row.basicLibrary != '1'" type="danger" text size="small"
						@click="handleDelete(scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!-- 分页 -->
		<div class="paging">
			<el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
				:page-size="queryPagination.pageSize" :total="queryPagination.total" :page-sizes="queryPagination.arrSize"
				@current-change="handleCurrentChange" @size-change="handleSizeChange" />
		</div>
		<div v-show="isCreated">
			<hr />
			<el-row justify="end">
				<el-button type="primary" @click="exportMatrixTableData">导出易损性矩阵</el-button>
				<el-button type="primary" @click="handleMoveIn()" v-show="isAdmin">移入基础库</el-button>
			</el-row>
			<h4>地震易损性矩阵</h4>
			<el-table class="listTables" ref="tableRef" border :data="tableDataMatrix" style="width: 100%"
				:cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
				<el-table-column prop="damage" label="破坏程度" align="right" width="150"><el-table-column prop="intensity"
						label="烈度" width="150"></el-table-column></el-table-column>
				<el-table-column header-align="center" align="center" label="基本完好" prop="bs">
					<template #default="scope">
						<el-input v-if="scope.row.isEdit" v-model="scope.row.bs" size="small"></el-input>
						<span v-else>{{ scope.row.bs }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="轻微破坏" prop="sl">
					<template #default="scope">
						<el-input v-if="scope.row.isEdit" v-model="scope.row.sl" size="small"></el-input>
						<span v-else>{{ scope.row.sl }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="中等破坏" prop="ml">
					<template #default="scope">
						<el-input v-if="scope.row.isEdit" v-model="scope.row.ml" size="small"></el-input>
						<span v-else>{{ scope.row.ml }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="严重破坏" prop="el">
					<template #default="scope">
						<el-input v-if="scope.row.isEdit" v-model="scope.row.el" size="small"></el-input>
						<span v-else>{{ scope.row.el }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="倒塌" prop="c">
					<template #default="scope">
						<el-input v-if="scope.row.isEdit" v-model="scope.row.c" size="small"></el-input>
						<span v-else>{{ scope.row.c }}</span>
					</template>
				</el-table-column>
			</el-table>
		</div>
	</div>
</template>

<script setup>
import { reactive, toRef, toRefs } from 'vue';
// 引入接口
import {
	queryBuildingsApi, // 分页查询
	queryPredictiveApi, //分页查询--预测数据
	queryFilterApi, //分页查询--筛选数据
	generateMatrixApi, // 生成易损性矩阵
	exportMatrixDataApi, // 导出易损性矩阵数据
	getVulnerabilityMatrix, //分页查询--生成的易损性矩阵
	matrix, //生成矩阵
	moveBasicLibrary, //移入/出基础库
	generatedExportMatrix, //生成的易损性矩阵--导出易损性矩阵
	deleteMatrixApi, //删除生成的易损性矩阵
	recalculateApi, //重新计算
} from '@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js';
// 引入省份和获取下级区域
import { getProvince, getChildArea } from '@/api/system/division';
// 自定义导出
import { downloadFile } from '@/utils/ruoyi';
// 状态管理模块
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 是否管理员
const isAdmin = computed(() => userStore.isAdmin || false);
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 获取当前实例
const { proxy } = getCurrentInstance();
// 全局路由对象
const router = useRouter();
// tab切换选中
const activeName = ref('1');
// 加载动画
let loading = ref(false);

// 变量
const data = reactive({
	// 表单参数
	params: {
		//intensity: '', //烈度
		//damage: '', //破坏程度
		// userName: userName.value, //维护人
		userName: '', //维护人
		//maintainerUnit: orgName.value, //维护人所属单位
		region: '', //区域
		use0: '', //用途
		use1: '',
		province: '', //省
		city: '', //市
		county: '', //县
		structureType: '', //结构类型
		structureType1: '',
		years: '', //建造年代
		fortification: '', //设防情况
		createStartTime: '', //维护开始时间
		createEndTime: '', //维护结束时间
		basicLibrary: '',//是否在基础库
		// 数据类型，默认:null（全部）
		dataSvType: null,
		// 是否已计算，0：未计算、1：已计算
		calculateOrNot: '',
	},
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions || [],
	//是否在基础库
	basicLibraryOptions: dictStore.basicLibraryOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 用途
	useOptions: dictStore.useOptions || [],
	// 用途联动选择
	use1Options: [],
	//是否已计算
	calculateOrNotOptions: [
		{
			value: '0',
			label: '否'
		},
		{
			value: '1',
			label: '是'
		},
	],

	// 表格数据
	tableData: [],
	// 表格选中数据
	multipleSelection: [],
	// 当前行数据
	curTableRow: {},
	// 分页工具栏
	layout: ' prev, pager, next, jumper, sizes, total',
	// 分页参数
	queryPagination: {
		pageNo: 1,
		pageSize: 10,
		total: 100,
		arrSize: [10, 20, 50, 100, 200, 500, 1000],
	},

	// 是否生成地震易损性矩阵
	isCreated: false,
	// 地震易损性矩阵表格
	tableDataMatrix: []
});
// 将一个响应式对象转换为一个普通对象
const {
	// 表单参数
	params,
	// 烈度选项
	//intensityOptions,
	// 设防情况选项
	fortificationOptions,
	// 建造年代选项
	yearsOptions,
	//是否在基础库
	basicLibraryOptions,
	// 结构类型选项
	structureTypeOptions,
	structureType1Options,
	// 用途选项
	useOptions,
	use1Options,
	// 是否已计算
	calculateOrNotOptions,
	// 表格数据
	tableData,
	// 表格选中数据
	multipleSelection,
	// 当前行数据
	curTableRow,
	// 分页数据
	queryPagination,
	// 分页工具栏
	layout
} = toRefs(data);

// 是否生成地震易损性矩阵
const isCreated = toRef(data, 'isCreated');
// 矩阵表格数据
const tableDataMatrix = toRef(data, 'tableDataMatrix');

/* 
	根据值获取用途
	params: {
		key: 值
	}
 */
function getUseByOptions(key) {
	const use = useOptions.value.find(item => item.value == key);
	return use ? (use.label || '') : '';
}
/* 
	根据值获取子用途
	params: {
		key1: 一级值
		key2: 二级值
	}
 */
function getChildUseByOptions(key1, key2) {
	const use = useOptions.value.find(item => item.value == key1);
	let childUse = {};
	if (use && use.children) {
		childUse = use.children.find(item => item.value == key2);
	}
	return childUse ? (childUse.label || '') : '';
}

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	// 下级区域
	getChildArea(value.id).then(response => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then(response => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}

// 禁用开始时间区间
const startDisableDate = time => {
	let endDateVal = params.value.createEndTime;
	if (endDateVal) {
		return time.getTime() > new Date(endDateVal).getTime();
	}
};
// 禁用开始时间区间
const endDisableDate = time => {
	let beginDateVal = params.value.createStartTime;
	if (beginDateVal) {
		return time.getTime() < new Date(beginDateVal).getTime();
	}
};
// 结构类型选择
const structureTypeChange = val => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		params.value.structureType1 = '';
		structureType1Options.value = structureTypes.children;
	}
};
// 切换用途
const useChange = val => {
	const use = useOptions.value.find(item => item.value === val);
	if (use) {
		params.value.use1 = '';
		use1Options.value = use.children;
	}
};

// tab切换
function handleClickTab(tab) {
	// console.log(tab.index); // 下标
	// console.log(tab.active); // 选中状态
	// console.log(tab.paneName); // 选中状态
	activeName.value = tab.paneName;
	// 注意：切换tab时，要将页码显示到第一页，每页显示行数默认为10条
	queryPagination.value.pageNo = 1;
	queryPagination.value.pageSize = 10;
	// 影藏易损性矩阵表格，要导出矩阵表格需重新生成矩阵数据
	isCreated.value = false;
	// 加载表格
	onSearch();
}
// 数据类型切换
function onChangeDataType(val) {
	onSearch();
}

//表格
const multipleTableRef = ref();
// 表格选择事件
const handleSelectionChange = val => {
	multipleSelection.value = val;
};
// 表格行点击事件
const rowClick = (row, column, event) => {
	if (multipleTableRef.value) {
		// 设置选中效果
		multipleTableRef.value.toggleRowSelection(row);
	}
	// 点击选中当前行
	curTableRow.value = row;
};

// 每页显示多少条数据
const handleSizeChange = val => {
	// 改变每页显示的条数
	queryPagination.value.pageSize = val;
	// 注意：在改变每页显示的条数时，要将页码显示到第一页
	queryPagination.value.pageNo = 1;
	onSearch();
};
// 选择当前页
const handleCurrentChange = val => {
	// 当前页数
	queryPagination.value.pageNo = val;
	onSearch();
};

// 跳转详情页
const jumpToInfo = (row) => {
	// router.push({
	// 	path: '/buildingVulnerAnalysis/statisticalAnalysis/info',
	// 	query: {
	// 		number: row.number,
	// 		dataType: row.dataType,
	// 		cbhdId: row.cbhdId,
	// 	}
	// });
	router.push({
		path: '/disasterDataManagement/maintainData/buildVulnerabilityInfo',
		query: {
			number: row.number,
			id: row.cbhdId,
		}
	});
}
// 跳转高层建筑详情页
const jumpToHighriseDetails = (row) => {
	router.push({
		path: '/buildingVulnerAnalysis/statisticalAnalysis/highriseBuildingState/highriseDetailsInterface',
		// 路由参数
		query: {
			number: row.number,
			dataType: row.dataType,
			pid: row.pid,
			isLook: true
		}
	});
}
// 跳转钢筋混凝土详情页
const jumpToReinforcedDetails = (row) => {
	router.push({
		path: '/buildingVulnerAnalysis/statisticalAnalysis/reinforcedState/reinforcedDetailsInterface', query: {
			number: row.number,
			dataType: row.dataType,
			pid: row.pid,
			isLook: true
		}
	});
}
// 跳转砖混结构详情页
const jumpToBrickDetails = (row) => {
	router.push({
		path: '/buildingVulnerAnalysis/statisticalAnalysis/brickState/brickDetailsInterface', query: {
			number: row.number,
			dataType: row.dataType,
			pid: row.pid,
			isLook: true
		}
	});
}
// 点击编号跳转至此数据的详细信息界面
const viewProject = row => {
	//生成的易损性矩阵
	if (activeName.value === '4') {
		if (row.isSpecification == '1') {
			proxy.$modal.msgWarning('样本数据不足，分析结果慎用！');
		}
		// 易损性矩阵表格数据
		tableDataMatrix.value = [];
		// 显示易损性矩阵表格
		isCreated.value = true;
		curMatrixId.value = row.matrixId
		// 生成矩阵
		matrix({
			//type: activeName.value // 震害数据1,预测数据2,筛选数据3
			matrixId: row.matrixId,
		}).then(res => {
			if (res.code == 200 && res.data) {
				let arr = [];
				if (res.data.length) {
					let obj = {};
					res.data.map((item, index) => {
						if (!obj[item.intensity]) {
							obj[item.intensity] = {
								intensity: item.intensity,
								damage: '',
								// 基本完好
								bs: '',
								// 轻微破坏sl
								sl: '',
								// 中等破坏ml
								ml: '',
								// 严重破坏el
								el: '',
								// 倒塌c
								c: ''
							};
						}
						switch (item.damage) {
							case '基本完好':
								obj[item.intensity].bs = item.rate;
								break;
							case '轻微破坏':
								obj[item.intensity].sl = item.rate;
								break;
							case '中等破坏':
								obj[item.intensity].ml = item.rate;
								break;
							case '严重破坏':
								obj[item.intensity].el = item.rate;
								break;
							case '倒塌':
								obj[item.intensity].c = item.rate;
								break;
							default:
								break;
						}
					});
					// 变量对象加入属性
					for (let key in obj) {
						arr.push(obj[key]);
					}
				}
				// 易损性矩阵表格数据
				tableDataMatrix.value = arr;
			} else {
				proxy.$modal.msgError('生成矩阵失败！');
			}
		}).catch(err => {
			console.log(err.message);
		});
	} else if (activeName.value === '1') {
		// 跳转详情页
		jumpToInfo(row);
	} else if (activeName.value === '2' || activeName.value === '3') {
		if (row.dataType === '钢筋混凝土参数信息') {
			// 跳转钢筋混凝土详情页
			jumpToReinforcedDetails(row);
		}
		else if (row.dataType === '高层建筑参数信息') {
			// 跳转高层建筑详情页
			jumpToHighriseDetails(row)
		}
		else if (row.dataType === '砖混结构参数信息') {
			// 跳转砖混结构详情页
			jumpToBrickDetails(row);
		}
		else {
			// 跳转详情页
			jumpToInfo(row);
		}
	}
}
//是否移出管理库
const handleRemove = (row) => {
	whetherToMove(row)
}
const curMatrixId = ref(null)
const handleMoveIn = () => {
	whetherToMove(curTableRow.value)
}
//移入传1，移除传0
const whetherToMove = (row) => {
	let query = {}
	if (activeName.value === '4') {
		query = {
			//...params.value,
			id: row.matrixId,
			//number: row.number,
			operate: row.basicLibrary === '1' ? '0' : '1',
			structureType: row.structureType,
			structureType1: row.structureType1,
			fortification: row.fortification,
			years: row.years,
			use0: row.use0,
			use1: row.use1,
			province: row.province,
			city: row.city,
			county: row.county,
			cs: row.cs
		}
	} else {
		query = {
			//...params.value,
			id: row.cbhdId,
			//number: row.number,
			operate: 1,
			structureType: row.structureType,
			structureType1: row.structureType1,
			fortification: row.fortification,
			years: row.years,
			use0: row.use0,
			use1: row.use1,
			province: row.province,
			city: row.city,
			county: row.county,
			cs: row.cs
		}
	}
	moveBasicLibrary(query).then((res) => {
		if (res.code === 200) {
			proxy.$modal.msgSuccess("成功!");
			row.basicLibrary = row.basicLibrary === '1' ? '0' : '1';
		}
	}).catch(err => {
		console.log(err.message);
	});
}
//删除生成的易损性矩阵
const handleDelete = (row) => {
	if (row.matrixId) {
		deleteMatrixApi({
			ids: row.matrixId || ''
		}).then(res => {
			const { code, data } = res;
			if (code == 200) {
				proxy.$modal.msgSuccess(data || '易损性矩阵删除成功！');
				// 刷新列表
				onSearch();
			}
		})
	}
}

// 建筑物区域特征信息维护表格查询
const onSearch = () => {
	loading.value = true;
	// 重置选中行列表
	multipleSelection.value.length = 0;
	switch (activeName.value) {
		case '2': // 预测
			//分页查询--预测数据
			queryPredictiveApi({
				...params.value,
				page: queryPagination.value.pageNo,
				rows: queryPagination.value.pageSize
			}).then(res => {
				loading.value = false;
				if (res.code === 200 && res.data) {
					// 分页总数
					queryPagination.value.total = res.data.total;
					tableData.value = res.data.rows.length ? res.data.rows : [];
				} else {
					// 分页总数
					queryPagination.value.total = 0;
					tableData.value = [];
				}
			}).catch(err => {
				loading.value = false;
				console.log(err);
			});
			break;
		case '3': // 筛选
			//分页查询--筛选数据
			queryFilterApi({
				...params.value,
				page: queryPagination.value.pageNo,
				rows: queryPagination.value.pageSize
			}).then(res => {
				loading.value = false;
				if (res.code === 200 && res.data) {
					// 分页总数
					queryPagination.value.total = res.data.total;
					tableData.value = res.data.rows.length ? res.data.rows : [];
				} else {
					// 分页总数
					queryPagination.value.total = 0;
					tableData.value = [];
				}
			}).catch(err => {
				loading.value = false;
				console.log(err);
			});
			break;
		case '4': // 生成的易损性矩阵
			//分页查询--生成的易损性矩阵
			getVulnerabilityMatrix({
				...params.value,
				page: queryPagination.value.pageNo,
				rows: queryPagination.value.pageSize
			}).then(res => {
				loading.value = false;
				if (res.code === 200 && res.data) {
					// 分页总数
					queryPagination.value.total = res.data.total;
					tableData.value = res.data.rows.length ? res.data.rows : [];
				} else {
					// 分页总数
					queryPagination.value.total = 0;
					tableData.value = [];
				}
			}).catch(err => {
				loading.value = false;
				console.log(err);
			});
			break;
		default:
			queryBuildingsApi({
				...params.value,
				page: queryPagination.value.pageNo,
				rows: queryPagination.value.pageSize
			}).then(res => {
				loading.value = false;
				if (res.code === 200 && res.data) {
					// 分页总数
					queryPagination.value.total = res.data.total;
					tableData.value = res.data.rows.length ? res.data.rows : [];
				} else {
					// 分页总数
					queryPagination.value.total = 0;
					tableData.value = [];
				}
			}).catch(err => {
				loading.value = false;
				console.log(err);
			});
			break;
	}
};
// 重置
const onRest = () => {
	proxy.resetForm('queryRef');
	onSearch();
};
// 导入
const onImport = () => {
	router.push({ path: '/disasterDataManagement/importData/buildingDamageData' });
};
// 重新计算
const onRecalculate = () => {
	// 选中的数据
	if (multipleSelection.value && multipleSelection.value.length) {
		let arrGC = [];
		let arrGH = [];
		let arrZH = [];
		multipleSelection.value.map((item, index) => {
			// 是否计算为'-'的数据不计算
			if (item.calculateOrNot == '0' || item.calculateOrNot == '1') {
				if (item.dataType.indexOf('高层') > -1) {
					arrGC.push(item.pid);
				} else if (item.dataType.indexOf('钢筋混凝土') > -1) {
					arrGH.push(item.pid);
				} else if (item.dataType.indexOf('砖混') > -1) {
					arrZH.push(item.pid);
				}
			}
		})
		if (arrGC.length || arrGH.length || arrZH.length) {
			let params = {};
			// 高层
			if (arrGC.length) {
				params["GC"] = arrGC.join(',')
			}
			// 钢混
			if (arrGH.length) {
				params["GH"] = arrGH.join(',')
			}
			// 砖混
			if (arrZH.length) {
				params["ZH"] = arrZH.join(',')
			}
			// 加载动画
			proxy.$modal.loading('正在努力计算,请耐心等待！');
			recalculateApi(params).then(res => {
				// 关闭加载动画
				proxy.$modal.closeLoading();
				// const { code, data } = res;
				proxy.$modal.msgSuccess('重新计算完成！');
			}).catch(err => {
				// 关闭加载动画
				proxy.$modal.closeLoading();
				console.log(err.message);
			})
		}
	} else {
		proxy.$modal.msgWarning('请选择数据行再计算！');
	}
}

// 生成易损性矩阵
function onCreateMatrix() {
	// 判断是否有选中行
	if (multipleSelection.value && multipleSelection.value.length) {
		// 易损性矩阵表格数据
		tableDataMatrix.value = [];
		// 获取选中行中的id组成新的数组
		const arrIds = getArrayIds(activeName.value == '1' ? 'cbhdId' : 'pid');
		// 生成矩阵
		generateMatrixApi({
			// 逗号隔开的id值(id1,id2,id3)
			ids: arrIds.join(','),
			type: activeName.value, // 震害数据1,预测数据2,筛选数据3
			// id: multipleSelection.value[0].pid,
			operate: multipleSelection.value[0].basicLibrary === '1' ? '1' : '0'
		}).then(res => {
			if (res.code == 200 && res.data) {
				proxy.$modal.msgSuccess('生成易损性矩阵成功！');
				const { id, data } = res.data;
				// 显示易损性矩阵表格
				isCreated.value = true;
				let arr = [];
				if (data.length) {
					let obj = {};
					data.map((item, index) => {
						if (!obj[item.intensity]) {
							obj[item.intensity] = {
								intensity: item.intensity,
								damage: '',
								// 基本完好
								bs: '',
								// 轻微破坏sl
								sl: '',
								// 中等破坏ml
								ml: '',
								// 严重破坏el
								el: '',
								// 倒塌c
								c: ''
							};
						}
						switch (item.damage) {
							case '基本完好':
								obj[item.intensity].bs = item.rate;
								break;
							case '轻微破坏':
								obj[item.intensity].sl = item.rate;
								break;
							case '中等破坏':
								obj[item.intensity].ml = item.rate;
								break;
							case '严重破坏':
								obj[item.intensity].el = item.rate;
								break;
							case '倒塌':
								obj[item.intensity].c = item.rate;
								break;
							default:
								break;
						}
					});
					// 变量对象加入属性
					for (let key in obj) {
						arr.push(obj[key]);
					}
				}
				// 易损性矩阵表格数据
				tableDataMatrix.value = arr;
			} else {
				proxy.$modal.msgError('生成矩阵失败！');
			}
		}).catch(err => {
			console.log(err.message);
		});
	} else {
		proxy.$modal.msgWarning('请选中行再生成矩阵！');
	}
}

// 获取选中行中的id组成新的数组
function getArrayIds(name) {
	let arrIds = [];
	// 判断是否有选中行
	if (multipleSelection.value && multipleSelection.value.length) {
		// 遍历获取id
		multipleSelection.value.map((item, index) => {
			arrIds.push(item[name]); // cbhdId
		});
	}
	return arrIds;
}
// 矩阵表格修改方法
function handleModify(index, row) {
	// console.log(index);
	// console.log(row);
	// 当前是修改状态，则应用保存，会提交数据
	if (row.isEdit) {
		proxy.$modal.msg('应用！');
	}
	// 当前不是修改状态则进行修改
	else {
		row.isEdit = true;
	}
}

// 导出矩阵列表数据
function exportMatrixTableData() {
	if (activeName.value === '4') {
		generatedExportMatrix({
			matrixId: curMatrixId.value
		}).then(res => {
			if (res) {
				let fileName = '易损性矩阵生成的易损性矩阵数据.xlsx';
				downloadFile(res, fileName);
			} else {
				proxy.$modal.msgError('导出易损性矩阵数据失败！');
			}
		}).catch(err => {
			proxy.$modal.msgError(err || '导出易损性矩阵数据失败！');
		});
	} else {
		// 获取选中行中的id组成新的数组
		const arrIds = getArrayIds('cbhdId');
		// 方式1：通用方法
		// proxy.download('/svAnalysis/exportMatrix?ids=' + arrIds.join(','), null, '易损性矩阵数据.xlsx');

		// 方式2：自定义下载
		// 逗号隔开的id值
		exportMatrixDataApi({
			ids: arrIds.join(','),
			type: activeName.value // 震害数据1,预测数据2,筛选数据3
		}).then(res => {
			if (res) {
				let fileName = '易损性矩阵震害数据.xlsx';
				switch (activeName.value) {
					case '2': // 预测
						fileName = '易损性矩阵预测数据.xlsx';
						break;
					case '3': // 筛选
						fileName = '易损性矩阵筛选数据.xlsx';
						break;
					default:
						fileName = '易损性矩阵震害数据.xlsx';
						break;
				}
				downloadFile(res, fileName);
			} else {
				proxy.$modal.msgError('导出易损性矩阵数据失败！');
			}
		}).catch(err => {
			proxy.$modal.msgError(err || '导出易损性矩阵数据失败！');
		});
	}
}

// 挂载完成
onMounted(() => {
	// 回显
	onSearch();
	// 获取行政区划数据
	getProvinceData();
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}
}

.paging {
	padding: 20px 0;
}

.form-inline {
	.el-form-item {
		margin-right: 0;
	}
}

:deep(.el-table.listTables) {
	thead.is-group th {
		background: none;
	}

	thead.is-group tr:first-of-type th:first-of-type {
		border-bottom: none;
	}

	thead.is-group tr:first-of-type th:first-of-type:before {
		content: '';
		position: absolute;
		width: 1px;
		height: 85px;
		/*这里需要自己调整，根据td的宽度和高度*/
		top: 0;
		left: 0;
		background-color: grey;
		opacity: 0.3;
		display: block;
		transform: rotate(302deg);
		/*这里需要自己调整，根据线的位置*/
		transform-origin: top;
	}

	thead.is-group tr:last-of-type th:first-of-type:before {
		content: '';
		position: absolute;
		width: 1px;
		height: 88px;
		/*这里需要自己调整，根据td的宽度和高度*/
		bottom: 0;
		right: 0;
		background-color: grey;
		opacity: 0.3;
		display: block;
		transform: rotate(302deg);
		/*这里需要自己调整，根据线的位置*/
		transform-origin: bottom;
		/* background:red; */
	}
}
</style>
